package com.tange.ai.iot.client.gnssa.utils.ble;


import com.tange.ai.iot.client.gnssa.utils.HexUtil;

import java.util.UUID;


public class BleConfig {
    public static final String SERVICE_UUID_STR = "0000A301-0000-1000-8000-00805f9b34fb";
    public static final String CHARACTERISTIC_WRITE_UUID_STR ="00002C12-0000-1000-8000-00805f9b34fb";
    public static final String CHARACTERISTIC_NOTIFY_UUID_STR = "00002C10-0000-1000-8000-00805f9b34fb";

    public static final UUID SERVICE_UUID = UUID.fromString(SERVICE_UUID_STR);
    public static final UUID CHARACTERISTIC_WRITE_UUID = UUID.fromString(CHARACTERISTIC_WRITE_UUID_STR);
    public static final UUID CHARACTERISTIC_NOTIFY_UUID = UUID.fromString(CHARACTERISTIC_NOTIFY_UUID_STR);

    /**
     * 计算CRC16校验码
     *
     * @param bytes
     * @return
     */

    public static byte[] calcCrc16(byte[] bytes){
        int CRC = 0x0000ffff;
        int POLYNOMIAL = 0x0000a001;

        int i, j;
        for (i = 0; i < bytes.length; i++) {
            CRC ^= ((int) bytes[i] & 0x000000ff);
            for (j = 0; j < 8; j++) {
                if ((CRC & 0x00000001) != 0) {
                    CRC >>= 1;
                    CRC ^= POLYNOMIAL;
                } else {
                    CRC >>= 1;
                }
            }
        }
        String s = HexUtil.algorismToHEXString(CRC);
        if(s.length()==2){
            s="00"+s;
        }
        return HexUtil.hexStringToBytes(s);
    }



    /**
     * 计算CRC16校验码
     *
     * @param bytes
     * @return
     */

    public static byte[] calcCrc16V2(byte[] bytes){

        int  n_Uart0CrcUserId = 0x1021;
        int U16_CRC=0;
        int i, U8_I;
        for (i = 0; i < bytes.length; i++) {
            for (U8_I = 0x80; U8_I !=0; U8_I>>=1) {

                if((U16_CRC & 0x8000)>0){
                    U16_CRC<<=1;
                    U16_CRC ^= n_Uart0CrcUserId;
                }else{
                    U16_CRC<<=1;
                }
                if ((bytes[i] & U8_I)>0) {
                    U16_CRC ^= n_Uart0CrcUserId;
                }
            }
        }
        U16_CRC= U16_CRC & 0xFFFF;
        String s = HexUtil.algorismToHEXString(U16_CRC);
        if(s.length()==2){
            s="00"+s;
        }
        return HexUtil.hexStringToBytes(s);
    }

}
